package com.jieshen;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

public class TalkClient {

    public static void main(String[] args) throws IOException {
        InputStream is = null;
        OutputStream os = null;
        ByteArrayOutputStream baos = null;
        Socket socket = null;
        Scanner s = new Scanner(System.in);
        String s1 = null;

        try {
            socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
            is = socket.getInputStream();
            os = socket.getOutputStream();
            while (true) {

                //发数据给服务器
                baos = new ByteArrayOutputStream();//相当于初始化
                s1 = s.nextLine();
                baos.write(s1.getBytes());
                os.write(baos.toByteArray());
                socket.shutdownOutput();//已经写完了


                //从服务器接收数据
                byte[] buffer = new byte[1];
                int len;
                //baos的初始化
                baos = new ByteArrayOutputStream();//相当于初始化
                while ((len = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                System.out.println(socket.getInetAddress().getHostAddress() + ": " + baos);
                if ("e".equalsIgnoreCase(s1) || "e".equalsIgnoreCase(baos.toString()))
                    break;
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            os.close();
            baos.close();
            socket.close();
            s.close();
        }

    }
}
